#include "feeditem.h"
#include "remotefilereader.h"

FeedItem::FeedItem(const FeedRSS& feedRSS, QSettings* settings):
        BlogItem(feedRSS.getFeedName(),feedRSS.getFeedUrl(),settings),
        _processingStatus(FeedItem::idle),
        _lastUpdate(QDate::currentDate())
{
}

FeedItem::FeedItem(const QDomElement& elt, QSettings* settings):
        BlogItem(elt.attribute("name"),
                 QUrl(elt.attribute("url")),
                 settings),
        _processingStatus(elt.attribute("status").toInt()),
        _lastUpdate(QDate::fromString(elt.attribute("lastUpdate")))
{
}


//Default processing method (update)
void FeedItem::defaultProcessing()
{
    this->update();
}

//Update method : get new mp3s
void FeedItem::update()
{
    //Update the RSS
    RemoteFileReader feedReader(_url);
    FeedRSS rss(feedReader.getContents());

    //Parse the feed
    QList<Mp3Item> mp3List = rss.getMp3s();

    //Add the new songs
    for( int i=0 ; i < mp3List.size() ; ++i )
    {
        //If the post is older than the last update, stop the updating
        if ( mp3List[i].getDatePosted() < this->getLastUpdate() )
        {
            break;
        }

        this->addSong(mp3List[i]);
    }

    //Change update date
    this->_lastUpdate = QDate::currentDate();
}

//Add a song to the feed, and to the model
void FeedItem::addSong(Mp3Item song)
{
    Mp3Item* staticSong = new Mp3Item(song);
    this->appendRow(staticSong);
}

//Getters / Setters
int FeedItem::getProcessingStatus() const
{
    return this->_processingStatus;
}

void FeedItem::setProcessingStatus(int status)
{
    this->_processingStatus = status;
}

QDate FeedItem::getLastUpdate() const
{
    return this->_lastUpdate;
}

//To XML
QDomElement FeedItem::toDomElt()
{
    QDomElement elt;
    elt.setTagName("Feed");
    elt.setAttribute("name",_name);
    elt.setAttribute("url",_url.toString());
    elt.setAttribute("status",_processingStatus);
    elt.setAttribute("lastUpdate",_lastUpdate.toString());

    return elt;
}
